package com.aa.springboot_aa.service.UserServiceImpl;

import com.aa.springboot_aa.pojo.User;
import com.aa.springboot_aa.pojo.dto.UserDto;
import com.aa.springboot_aa.repository.UserRepository;
import com.aa.springboot_aa.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service  //标记成了spring的bean
public class UserService implements IUserService {


    @Autowired
    UserRepository userRepository;

    @Override
    public User add(UserDto user) {

        User userpojo = new User();
        BeanUtils.copyProperties(user,userpojo);//拷贝
        userRepository.save(userpojo);
        //调用数据访问类

        return userpojo;
    }

    @Override
    public User getUser(Integer Id) {
        return userRepository.findById(Id).orElseThrow(()->{   //返回值为Optional专门用来处理空指针
            throw new IllegalArgumentException("用户不存在，参数异常");  //抛出异常
        });

    }

    @Override
    public User edit(UserDto user) {
        User userPojo = new User();
        BeanUtils.copyProperties(user,userPojo);

        return userRepository.save(userPojo);
    }

    @Override
    public void delete(Integer Id) {
         userRepository.deleteById(Id);
    }

}
